
// // 超时
// var findAnagrams = function(s, p) {
//   const len = s.length;
//   if (len < p.length) return [];

//   let ans = [], left = 0, right = p.length;
//   const s1 = p.split("").sort().join("");

//   while (right <= len) {
//     const str = s.substring(left, right);
    
//     if (isDiff(str, s1)) {
//       ans.push(left);
//     }
//     left++, right++;
//   }
//   return ans;
// };

// function isDiff(subStr, s1) {
//   const s2 = subStr.split("").sort().join("");
//   return s1 == s2;
// }


var findAnagrams = function(s, p) {
  const len = s.length;
  if (len < p.length) return [];

  let ans = [];
  const pCount = new Array(26).fill(0);
  const sCount = new Array(26).fill(0);

  for (let i = 0; i < p.length; i++) {
    pCount[p[i].charCodeAt() - 'a'.charCodeAt()]++;
    sCount[s[i].charCodeAt() - 'a'.charCodeAt()]++;
  }

  // 长度相等了，判断是不是异位词
  if (pCount.join("") === sCount.join("")) {
    ans.push(0);
  }

  // 滑动窗口遍历
  for (let i = p.length; i < len; i++) {
    sCount[s[i].charCodeAt() - 'a'.charCodeAt()]++;
    sCount[s[i - p.length].charCodeAt() - 'a'.charCodeAt()]--;

    if (pCount.join("") === sCount.join("")) {
      ans.push(i - p.length + 1);
    }
  }
  return ans;
}


const s = "cbaebabacd", p = "abc";
console.log(findAnagrams(s,p))